function [gg1,gg2] = avg_inf_510(A,bt,pi_bar,pi_lim)

h1 = 5; h2 = 10;                                                            % both need to be > 1
g = A(bt,:)';
pi = pi_bar;
s = size(pi_bar,1);
bin = (1:s)';
tol = 1e-7;
for i = 2:h2
    pi = pi*(i-1)/i + pi_bar'/i;
    g = g.*A(bin,:);
    bin = repmat((1:s),size(g,1),1);
    pi = pi(:); bin = bin(:); g = g(:);
    d = [pi bin];
    [d,~,ic] = uniquetol(d,tol,'ByRows',true);
    dr = size(d,1);
    d = [d -ones(dr,1)]; %#ok<AGROW>
    
    for j = 1:dr
        d(j,3) = sum(g(ic==j,1));
    end
    d(d(:,3)==0,:) = [];
    pi = d(:,1); bin = d(:,2); g = d(:,3);
    if i == h1
        pi1 = pi; g1 = g;
    end
end
pi2 = pi; g2 = g;

bin1 = (pi_lim'-pi1>-tol); bin1  = s+1 - sum(bin1,2);
bin2 = (pi_lim'-pi2>-tol); bin2  = s+1 - sum(bin2,2);
gg1 = zeros(s,1);
gg2 = zeros(s,1);
for i = 1:s
    gg1(i,1) = sum(g1(bin1==i,1));
    gg2(i,1) = sum(g2(bin2==i,1));
end
